package kr.co.bettersoftportal.site.management.controller;


import kr.co.bettersoftportal.site.domain.Comment;
import kr.co.bettersoftportal.site.domain.CommunityBoard;
import kr.co.bettersoftportal.site.domain.Member;
import kr.co.bettersoftportal.site.domain.NoticeBoard;
import kr.co.bettersoftportal.site.management.service.BettersoftPortalService;
import kr.co.bettersoftportal.site.management.service.CommentService;
import kr.co.bettersoftportal.site.management.service.CommunityBoardService;
import kr.co.bettersoftportal.site.management.service.NoticeBoardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 게시판 커멘트 기능을 관리하는 컨트롤러
 * 어떤 게시판 인지는 JSP 페이지에서 파라미터를 받아와 결정한다
 */
public class CommentController extends MultiActionController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private BettersoftPortalService bettersoftPortalService = null;

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private CommentService commentService = null;

    @Autowired
    private CommunityBoardService communityBoardService  = null;

    @Autowired
    private NoticeBoardService noticeBoardService = null;



    /**
     *
     * Comment 관련 Method
     *
     * Flag
     *
     * 1 : community board
     * 2 : photo board
     * 3 : notice
     *
     */

    /**
     * Comment 작성
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    public ModelAndView commentWrite(HttpServletRequest request, HttpServletResponse response) throws Exception{


        Comment comment = new Comment();
        bind(request, comment);

        Member member = new Member();

        /**
         * Null 에러 방지용 공백 전환
         */
        if(request.getParameter("writer_id") == null){
            return new ModelAndView("index");
        }

        if(request.getParameter("commentContent") == null){
            return new ModelAndView("index");
        }

        if(request.getParameter("commentDB") == null){
            return new ModelAndView("index");
        }

        // id 로 멤버의 정보를 받아온다.
        member = bettersoftPortalService.getMemberById(request.getParameter("writer_id"));

        // DB에 입력할 comment 객체에 정보를 주입
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());

        comment.setRegister_date(strDate);
        comment.setModify_date(strDate);
        comment.setActivate_yn("Y");
        comment.setContent(request.getParameter("commentContent"));
        comment.setPassword(member.getPASSWORD());
        comment.setWriter_nick_name(member.getNAME());
        comment.setComment_db_name(request.getParameter("commentDB"));

        logger.info("commentWrite");
        logger.info("boardno   : {}", comment.getBoard_no());
        logger.info("id        : {}", comment.getWriter_id());
        logger.info("nickName  : {}", comment.getWriter_nick_name());
        logger.info("commentDB : {}", comment.getComment_db_name());

        String result = "";

        // DB에 comment 작성
        result = commentService.writeComment(comment);
        // 어느 게시판인지 flag 를 이용하여 식별
        String flag = request.getParameter("flag");

        if(result.equals("1")){
            if(flag.equals("1")){ // community board comment 일 경우
                CommunityBoard tempBoard = new CommunityBoard();
                /**
                 * comment 작성에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
                 * comment 카운트를 +1 한다.
                 */
                tempBoard = communityBoardService.getBoardByNo(request.getParameter("board_no"));
                int updateCount = Integer.parseInt(tempBoard.getReply_count());
                updateCount = updateCount + 1;
                tempBoard.setReply_count(Integer.toString(updateCount));

                String replyUpdateResult = "";

                replyUpdateResult = communityBoardService.updateReplyCount(tempBoard);
                logger.info("result    : {}", replyUpdateResult);

            }else if(flag.equals("2")){ // photo board comment 일 경우
//                PhotoBoard tempPBoard = new PhotoBoard();
//                /**
//                 * comment 작성에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
//                 * comment 카운트를 +1 한다.
//                 */
//                tempPBoard = photoBoardService.getBoardByNo(request.getParameter("board_no"));
//                int updateCount = Integer.parseInt(tempPBoard.getReply_count());
//                updateCount = updateCount + 1;
//                tempPBoard.setReply_count(Integer.toString(updateCount));
//
//                String replyUpdateResult = "";
//
//                replyUpdateResult = photoBoardService.updateReplyCount(tempPBoard);
//                logger.info("result    : {}", replyUpdateResult);

            }else if(flag.equals("3")){ // notice board comment 일 경우
                NoticeBoard tempNBoard = new NoticeBoard();
                /**
                 * comment 작성에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
                 * comment 카운트를 +1 한다.
                 */
                tempNBoard = noticeBoardService.getBoardByNo(request.getParameter("board_no"));
                int updateCount = Integer.parseInt(tempNBoard.getReply_count());
                updateCount = updateCount + 1;
                tempNBoard.setReply_count(Integer.toString(updateCount));

                String replyUpdateResult = "";

                replyUpdateResult = noticeBoardService.updateReplyCount(tempNBoard);
                logger.info("result    : {}", replyUpdateResult);

            }
        }




        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:" + request.getParameter("nextTarget"));
        return mav;
    }

    /**
     * Comment 삭제
     * Activate_yn = n
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commentDelete(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Comment comment = new Comment();
        bind(request, comment);

        Member member = new Member();

        HttpSession s = request.getSession(false); // 세션으로 부터 ID 를 받아온다


        /**
         * Null 에러 방지용 공백 전환
         */
        if(request.getParameter("board_no") == null){
            return new ModelAndView("index");
        }

        if(request.getParameter("commentDB") == null){
            return new ModelAndView("index");
        }

        // id 로 멤버의 정보를 받아온다.
        member = bettersoftPortalService.getMemberById((String)s.getAttribute("userId"));



        // DB에 해당 Comment 의 activate 를 n 으로 설정한다. 필요한 정보들을 주입
        comment.setActivate_yn("N");
        comment.setBoard_no(request.getParameter("board_no"));
        comment.setPassword(member.getPASSWORD());
        comment.setComment_db_name(request.getParameter("commentDB"));


        String result = "";

        // DB에 comment 삭제 (activate n)
        result = commentService.deleteComment(comment);

        String flag = request.getParameter("flag");

        logger.info("commentDelete");
        logger.info("boardno   : {}", comment.getBoard_no());
        logger.info("id        : {}", comment.getWriter_id());
        logger.info("nickName  : {}", comment.getWriter_nick_name());
        logger.info("commentDB : {}", comment.getComment_db_name());





        if(result.equals("1")){
            if(flag.equals("1")){ // community board comment 일 경우
                CommunityBoard tempBoard = new CommunityBoard();
                /**
                 * comment 삭제에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
                 * comment 카운트를 -1 한다.
                 */
                tempBoard = communityBoardService.getBoardByNo(request.getParameter("board_no"));
                int updateCount = Integer.parseInt(tempBoard.getReply_count());
                updateCount = updateCount - 1;
                tempBoard.setReply_count(Integer.toString(updateCount));

                String replyUpdateResult = "";

                replyUpdateResult = communityBoardService.updateReplyCount(tempBoard);
                logger.info("result    : {}", replyUpdateResult);



            }else if(flag.equals("2")){ // photo board comment 일 경우
//                PhotoBoard tempPBoard = new PhotoBoard();
//                /**
//                 * comment 삭제에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
//                 * comment 카운트를 -1 한다.
//                 */
//                tempPBoard = photoBoardService.getBoardByNo(request.getParameter("board_no"));
//                int updateCount = Integer.parseInt(tempPBoard.getReply_count());
//                updateCount = updateCount - 1;
//                tempPBoard.setReply_count(Integer.toString(updateCount));
//
//                String replyUpdateResult = "";
//
//                replyUpdateResult = photoBoardService.updateReplyCount(tempPBoard);
//                logger.info("result    : {}", replyUpdateResult);


            }else if(flag.equals("3")){ // notice board comment 일 경우
                NoticeBoard tempNBoard = new NoticeBoard();
                /**
                 * comment 삭제에 성공한 경우 board_no 을 이용해 게시물을 얻어온 후
                 * comment 카운트를 -1 한다.
                 */
                tempNBoard = noticeBoardService.getBoardByNo(request.getParameter("board_no"));
                int updateCount = Integer.parseInt(tempNBoard.getReply_count());
                updateCount = updateCount - 1;
                tempNBoard.setReply_count(Integer.toString(updateCount));

                String replyUpdateResult = "";

                replyUpdateResult = noticeBoardService.updateReplyCount(tempNBoard);
                logger.info("result    : {}", replyUpdateResult);

            }
        }

        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:" + request.getParameter("nextTarget"));
        return mav;
    }


    /**
     * Comment 내용 수정
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commentUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Comment comment = new Comment();
        bind(request, comment);

        CommunityBoard board = new CommunityBoard();
        Member member = new Member();

        HttpSession s = request.getSession(false); // 세션으로 부터 ID 를 받아온다


        try{
            /**
             * Null 에러 방지용 공백 전환
             */
            if((String)s.getAttribute("userId") == null){
                return new ModelAndView("index");
            }

            if(request.getParameter("content") == null){
                return new ModelAndView("index");
            }

            if(request.getParameter("board_no") == null){
                return new ModelAndView("index");
            }

            if(request.getParameter("comment_no") == null){
                return new ModelAndView("index");
            }

            if(request.getParameter("commentDB") == null){
                return new ModelAndView("index");
            }



        }catch (NullPointerException e){
            return new ModelAndView("redirect:index.do");

        }



        // id 로 멤버의 정보를 받아온다.
        member = bettersoftPortalService.getMemberById((String)s.getAttribute("userId"));

        // DB에 해당 Comment 의 activate 를 n 으로 설정한다. 필요한 정보들을 주입
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());

        comment.setActivate_yn("Y");
        comment.setModify_date(strDate);
        comment.setContent(request.getParameter("content"));
        comment.setBoard_no(request.getParameter("board_no"));
        comment.setPassword(member.getPASSWORD());
        comment.setComment_no(request.getParameter("comment_no"));
        comment.setComment_db_name(request.getParameter("commentDB"));

        logger.info("commentUpdate");
        logger.info("boardno   : {}", comment.getBoard_no());
        logger.info("id        : {}", comment.getWriter_id());
        logger.info("nickName  : {}", comment.getWriter_nick_name());
        logger.info("commentDB : {}", comment.getComment_db_name());



        String result = "";

        // 수정된 comment 의 내용을 DB 에 기록한다.
        result = commentService.updateComment(comment);

        logger.info("result    : {}", result);



        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:" + request.getParameter("nextTarget"));
        return mav;
    }



    ///////////////////////////////////////
    // Spring Framework Setter Injection //
    ///////////////////////////////////////

}
